package com.kly.user.db.dao.impl;
import com.fqgj.common.base.AbstractBaseMapper;
import com.fqgj.common.utils.CollectionUtils;
import com.google.common.collect.Maps;
import com.kly.user.db.dao.UserMsgUnreadNumDao;
import com.kly.user.db.entity.UserMsgUnreadNumEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;

/**
* User: linqu
* Date: 2023-09-27
* Time: 19:19:08.954
*/

@Slf4j
@Repository
public class UserMsgUnreadNumDaoImpl extends AbstractBaseMapper<UserMsgUnreadNumEntity> implements UserMsgUnreadNumDao {

    @Override
    public int saveUnReadMsgNum(String fromUserCode, String toUserCode, String sessionId, String chatterUserCode) {
        try {
            final HashMap<String, Object> params = Maps.newHashMap();
            params.put("fromUserCode", fromUserCode);
            params.put("toUserCode", toUserCode);
            final List<UserMsgUnreadNumEntity> userMsgUnreadNumEntities = this.selectByParams(params);
            if (CollectionUtils.isEmpty(userMsgUnreadNumEntities)) {
                UserMsgUnreadNumEntity entity = new UserMsgUnreadNumEntity();
                entity.setChatterUserCode(chatterUserCode);
                entity.setSessionId(sessionId);
                entity.setUnreadNum(1);
                entity.setFromUserCode(fromUserCode);
                entity.setToUserCode(toUserCode);
                this.insert(entity);
                return 1;
            }
            final UserMsgUnreadNumEntity updateEntity = userMsgUnreadNumEntities.get(0);
            updateEntity.setUnreadNum(updateEntity.getUnreadNum() + 1);
            return this.updateByPrimaryKey(updateEntity);
        } catch (Exception e) {
            log.error("saveUnReadMsgNumError, userCode:{}, toUserCode:{}, sessionId:{}", fromUserCode, toUserCode, sessionId, e);
        }
        return 0;
    }

    @Override
    public int readMessage(String fromUserCode, String toUserCode) {
        final HashMap<String, Object> params = Maps.newHashMap();
        params.put("fromUserCode", fromUserCode);
        params.put("toUserCode", toUserCode);
        log.info("readMessageInfo, fromUserCode:{}, toUserCode:{}", fromUserCode, toUserCode);
        return this.getSqlSession().update(this.getStatement(".readMessage"), params);
    }

    @Override
    public int clearAllUnreadMessageForInvalidAccount() {
        return this.getSqlSession().delete(this.getStatement("clearAllUnreadMessageForInvalidAccount"));
    }

    @Override
    public List<UserMsgUnreadNumEntity> listModelUnreadReadMsgNum(List<String> modelCodes) {
        final HashMap<String, Object> params = Maps.newHashMap();
        params.put("modelCodes", modelCodes);
        return this.getSqlSession().selectList(this.getStatement("listModelUnreadReadMsgNum"), params);
    }
}